package com.gzsxy.sso.core.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gzsxy.sso.common.dto.request.UserRequest;
import com.gzsxy.sso.common.dto.response.UserRsp;
import com.gzsxy.sso.common.exception.impl.CustomAssert;
import com.gzsxy.sso.common.result.ResultCodeEnum;
import com.gzsxy.sso.common.utils.Base64Util;
import com.gzsxy.sso.core.dao.UserRoleMapper;
import com.gzsxy.sso.core.entity.Permission;
import com.gzsxy.sso.core.entity.User;
import com.gzsxy.sso.core.dao.UserMapper;
import com.gzsxy.sso.core.entity.UserRole;
import com.gzsxy.sso.core.entity.vo.UserQueryVo;
import com.gzsxy.sso.core.model.SessionUser;
import com.gzsxy.sso.core.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzsxy.sso.core.utils.SessionUserUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.swing.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 * @author zxl
 * @since 2021-11-10
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final static Logger log = LoggerFactory.getLogger(UserServiceImpl.class);


    @Autowired
    private UserMapper userMapper;


    @Autowired
    private UserRoleMapper userRoleMapper;







    /**
     * @description: 根据用户id查询用户
     * @param id
     * @return
     */
    @Override
    public User getUserById(String id) {
        User user = userMapper.selectById(id);
        return user;
    }

    /**
     * @description: 通过用户名查询用户
     * @param username 用户名
     * @return  user
     */
    @Override
    public User findByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_name",username);
        User user = userMapper.selectOne(queryWrapper);
        return user;
    }

    /**
     * @description: 通过身份证号查询用户
     * @param idcard 身份证号
     * @return  user
     */
    @Override
    public User findByIdCard(String idcard) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id_card",idcard);
        User user = userMapper.selectOne(queryWrapper);
        return user;
    }

    /**
     * @description: 通过用户名查询当前用户权限
     * @param  username 用户名
     * @return Permission 权限
     */
    @Override
    public List<Permission> findPermissionByUsername(String username) {
        return userMapper.findPermissionByUsername(username);
    }

    /**
     * @description: 获取所有的用户
     */
    @Override
    public List<User> getAllUser() {
       return userMapper.getAllUser();
    }




    /**
     * @description: 分页查询
     * @param
     * @return
     */
    @Override
    public IPage<UserRsp> selectPage(IPage<?> pageParam, UserQueryVo userQueryVo) {
        //显示分页查询列表
        // 1.排序：按照sort字段排序
        QueryWrapper<UserRsp> queryWrapper = new QueryWrapper<>();//条件构造器
        queryWrapper.orderByDesc("sort");//通过sort字段进行升序
        queryWrapper.eq("is_deleted",0);

        //2.分页查询
        if (userQueryVo == null){
            IPage<UserRsp> userRsps = baseMapper.selectPageByuserQueryVo(pageParam, queryWrapper);

            //将userRsps设置到pageParm中  setRecords会计算总的数据
            return userRsps;
        }
        //3.根据条件进行查询
        String id = userQueryVo.getId();
        String realName = userQueryVo.getRealName();
        String joinDateBegin = userQueryVo.getJoinDateBegin();
        String joinDateEnd = userQueryVo.getJoinDateEnd();

        String userName = userQueryVo.getUserName();
        String idCard = userQueryVo.getIdCard();


        //根据用户id查询
        if (StringUtils.isNotEmpty(id)){
            queryWrapper.likeRight("id",id);
        }
        //用户名
        if (StringUtils.isNotEmpty(userName)){
            queryWrapper.likeRight("user_name",userName);
        }
        //身份证号
        if (StringUtils.isNotEmpty(id)){
            queryWrapper.likeRight("id_card",idCard);
        }
        //用户真实姓名模糊查询
        if (StringUtils.isNotEmpty(realName)){
            queryWrapper.likeRight("real_name",realName);
        }
        //时间大于等于
        if (StringUtils.isNotEmpty(joinDateBegin)){
            queryWrapper.ge("create_time",joinDateBegin);
        }
        //时间小于等于 根据join_date字段进行比较
        if (StringUtils.isNotEmpty(joinDateEnd)){
            queryWrapper.le("create_time",joinDateEnd);
        }
        IPage<UserRsp> userRsps = baseMapper.selectPageByuserQueryVo(pageParam, queryWrapper);

        //将userRsps设置到pageParm中  setRecords会计算总的数据
        return userRsps;



    }

    /**
     * @description: 删除用户
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class) //添加事务配置 异常回滚
    @Override
    public Boolean deleteById(String id) {
        User user = baseMapper.selectById(id);
        //用户不存在，抛出异常
        CustomAssert.notTrue(com.baomidou.mybatisplus.core.toolkit.ObjectUtils.isNotEmpty(user),ResultCodeEnum.USER_NOT_FOUND.getMessage(),ResultCodeEnum.USER_NOT_FOUND.getCode());
        //查询出当前用户的所有角色
        List<UserRole> userRoles = userRoleMapper.exisByUserId(id);
        //获取所有的id
        List<String> idList = userRoles.stream().map(UserRole::getId).collect(Collectors.toList());
        //批量删除用户对应的角色
        userRoleMapper.deleteBatchIds(idList);

        //获取当前登录用户
//        SessionUser sessionUser = SessionUserUtil.getSessionUser();
//        user.setUpdateUser(sessionUser.getUserName());
        baseMapper.updateById(user);
        int i = baseMapper.deleteById(id);
        if (i == 0){
            return  false;
        } else {
            return  true;
        }
    }

    /**
     * @description: 查询当前用户是否为超级管理员
     * @param
     * @return
     */
    @Override
    public Boolean isSadmin(String userId) {
        return baseMapper.isSadmin(userId);
    }



    /**
     * @description: 添加用户
     * @param user 用户信息
     * @return
     */
    @Transactional(rollbackFor = Exception.class) //添加事务配置 异常回滚
    @Override
    public void addUser(UserRequest user) {
        //用户名唯一校验
        User user1 = findByUsername(user.getUserName());
        CustomAssert.notTrue(ObjectUtils.isEmpty(user1), ResultCodeEnum.USER_LOGIN_ID_EXIST.getMessage(), ResultCodeEnum.USER_LOGIN_ID_EXIST.getCode());
        //身份证号唯一校验
        User user2 = findByIdCard(user.getIdCard());
        CustomAssert.notTrue(ObjectUtils.isEmpty(user2), ResultCodeEnum.USER_ID_CARD_EXIST.getMessage(), ResultCodeEnum.USER_ID_CARD_EXIST.getCode());

        User user3 = new User();
        BeanUtils.copyProperties(user,user3);
        //对密码进行加密
        String password = user3.getPassword();
        String str = Base64Util.encryptToMD5(password);
        user3.setPassword(Base64Util.encode(str));
        //添加用户信息
        baseMapper.insert(user3);
//        //关联角色信息
//        setRoleInfo(user3);

    }

    /**
     * @description: 编辑用户
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class) //添加事务配置 异常回滚
    @Override
    public void updateUser(UserRequest request) {
        User olduser = getUserById(request.getId());
        //用户名不存在
        CustomAssert.notNull(olduser,ResultCodeEnum.USER_NOT_FOUND.getMessage(),ResultCodeEnum.USER_NOT_FOUND.getCode());

        User user = new User();
        BeanUtils.copyProperties(request,user);

        //修改登录名--唯一登录名校验
        if (user.getUserName() != null && !user.getUserName().equals(olduser.getUserName())){
            User user1 = findByUsername(user.getUserName());
            CustomAssert.notTrue(ObjectUtils.isEmpty(user1), ResultCodeEnum.USER_LOGIN_ID_EXIST.getMessage(), ResultCodeEnum.USER_LOGIN_ID_EXIST.getCode());
        }
        //修改身份证号--唯一身份证号校验
        if (user.getIdCard() != null && !user.getIdCard().equals(olduser.getIdCard())){
            User user2 = findByIdCard(user.getIdCard());
            CustomAssert.notTrue(ObjectUtils.isEmpty(user2), ResultCodeEnum.USER_ID_CARD_EXIST.getMessage(), ResultCodeEnum.USER_ID_CARD_EXIST.getCode());
        }
        //如果未修改密码
        if (StringUtils.isBlank(user.getPassword())){
            user.setPassword(olduser.getPassword());
        }
        user.setDeleted(olduser.getDeleted());

        userMapper.updateById(user);

    }


    /**
     * @description: 禁用账号
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class) //添加事务配置 异常回滚
    @Override
    public void changeDisabled(String userId, Boolean type) {
        User user = this.getUserById(userId);
        //用户名不存在
        CustomAssert.notNull(user,ResultCodeEnum.USER_NOT_FOUND.getMessage(),ResultCodeEnum.USER_NOT_FOUND.getCode());
        //设置是否禁用账号
        user.setFreeze(type);
        baseMapper.updateById(user);


    }


    /**
     * @description: 根据关键字查询用户名列表
     * @param
     * @return
     */
    @Override
    public List<Map<String, Object>> selectNameListByKey(String key) {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.select(User::getRealName);
        wrapper.likeRight(User::getRealName,key);
        //select real_name from t_user where real_name like "周%"
        List<Map<String, Object>> list = baseMapper.selectMaps(wrapper);
        return list;
    }


    /**
     * @description: 更新最后登录时间
     * @param  id 用户id
     * @return
     */
    @Override
    public void updateLastloginTime(String id) {
        User olduser = getUserById(id);
        //用户名不存在
        CustomAssert.notNull(olduser,ResultCodeEnum.USER_NOT_FOUND.getMessage(),ResultCodeEnum.USER_NOT_FOUND.getCode());
        //设置更新最后登录时间
        baseMapper.updateLastloginTime(olduser);
    }


    /**
     * 修改密码
     * @param oldPassword 原密码
     * @param password 新密码
     */
    @Override
    public void changePassword(String oldPassword,String password) {
        SessionUser sessionUser = SessionUserUtil.getSessionUser();
        //原密码校验
        CustomAssert.notTrue( userMapper.selectUserById(sessionUser.getId(),oldPassword),ResultCodeEnum.OLDPASSWORD_ERROR.getMessage());
        //更新密码
        baseMapper.updatePassword(sessionUser.getId(),password);
    }

    /**
     * @description: 关联角色信息
     * @param
     * @return
     */
    private void setRoleInfo(User user){
        UserRole userRole = new UserRole();
        //执行insert后mybatis会自动回填一个id
        userRole.setUserId(user.getId());
        //获取角色id列表
        List<String> roleIds = user.getRoleId();
        roleIds.forEach(role ->{
            userRole.setRoleId(role);
            userRoleMapper.insert(userRole);
                });
    }



    /**
     * @description: 对外暴露接口，更新用户信息返回最新用户
     * @param
     * @return
     */
    @Override
    public UserRsp updateApiUser(UserRequest request) {
        this.updateUser(request);
        UserRsp userRsp = new UserRsp();
        User user = userMapper.selectById(request.getId());
        BeanUtils.copyProperties(user,userRsp);
        return userRsp;
    }


    /**
     * @description: 编辑账号余额
     * @param
     * @return
     */
    @Override
    public void editAmountById(String id, Integer amount) {
        User user = userMapper.selectById(id);
        user.setAmount(user.getAmount()+amount);
        userMapper.updateById(user);
    }


    /**
     * @description: 对外接口新增用户
     * @param
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addUser1(UserRequest user) {
        log.info("appCode=esjy----接收到新增用户[{}]", JSON.toJSONString(user));
        //用户名唯一校验
        User user1 = findByUsername(user.getUserName());
        CustomAssert.notTrue(ObjectUtils.isEmpty(user1), ResultCodeEnum.USER_LOGIN_ID_EXIST.getMessage(), ResultCodeEnum.USER_LOGIN_ID_EXIST.getCode());
        //身份证号唯一校验
        User user2 = findByIdCard(user.getIdCard());
        CustomAssert.notTrue(ObjectUtils.isEmpty(user2), ResultCodeEnum.USER_ID_CARD_EXIST.getMessage(), ResultCodeEnum.USER_ID_CARD_EXIST.getCode());

        User user3 = new User();
        BeanUtils.copyProperties(user,user3);
        List<String> roleId = new ArrayList<>();
        //商家角色id
        roleId.add("1483789439641686018");
        user3.setRoleId(roleId);
        //添加用户信息
        baseMapper.insert(user3);
        //关联角色信息
        setRoleInfo(user3);
    }

    /**
     * @description: 查询当前系统的所有商家
     * @param
     * @return
     */
    @Override
    public List<String> selectAllUserId() {
        LambdaQueryWrapper<User> wrapper = Wrappers.lambdaQuery();
        wrapper.select(User::getId);
        return baseMapper.selectObjs(wrapper).stream().map(o -> (String)o).collect(Collectors.toList());
    }
}
